package com.graduate.emos.wx.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.graduate.emos.wx.common.util.R;
import com.graduate.emos.wx.config.shiro.JwtUtil;
import com.graduate.emos.wx.controller.form.*;
import com.graduate.emos.wx.db.pojo.MessageEntity;
import com.graduate.emos.wx.exception.EmosException;
import com.graduate.emos.wx.service.MessageService;
import com.graduate.emos.wx.task.MessageTask;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/message")
@Api("消息模块网络接口")
public class MessageController {
    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private MessageService messageService;

    @Autowired
    private MessageTask messageTask;

    @PostMapping("/searchMessageByPage")
    @ApiOperation("获取分页消息列表")
    public R searchMessageByPage(@Valid @RequestBody SearchMessageByPageForm form, @RequestHeader String token) {
        int userId = jwtUtil.getUserId(token);
        int page = form.getPage();
        int length = form.getLength();
        long start = (page - 1) * length;
        List<HashMap> list = messageService.searchMessageByPage(userId, start, length);
        return R.ok().put("result", list);
    }

    @PostMapping("/searchMessageById")
    @ApiOperation("根据id查询消息")
    public R searchMessageById(@Valid @RequestBody SearchMessageByIdForm form, @RequestHeader String token) {
        HashMap map = messageService.searchMessageById(form.getId());
        return R.ok().put("result", map);
    }

    @PostMapping("/updateUnreadMessage")
    @ApiOperation("未读消息更新已读消息")
    public R updateUnreadMessage(@Valid @RequestBody UpdateUnreadMessageForm form, @RequestHeader String token) {
        long rows = messageService.updateUnreadMessage(form.getId());
        return R.ok().put("result", rows == 1 ? true : false);
    }

    @PostMapping("/deleteMessageRefById")
    @ApiOperation("删除信息")
    public R deleteMessageRefById(@Valid @RequestBody DeleteMessageRefByIdForm form, @RequestHeader String token) {
        long rows = messageService.deleteMessageRefById(form.getId());
        return R.ok().put("result", rows == 1 ? true : false);
    }

    @GetMapping("/refreshMessage")
    @ApiOperation("刷新用户的消息")
    public R refreshMessage(@RequestHeader("token") String token) {
        /*从token中解析用户id*/
        int userId = jwtUtil.getUserId(token);
        /*异步接收消息*/
        messageTask.receiveAsync(userId + "");
        /*查询接收了多少条消息*/
        long lastRows = messageService.searchLastCount(userId);
        /*查询未读数据*/
        long unreadRows = messageService.searchUnreadCount(userId);
        return R.ok().put("lastRows", lastRows).put("unreadRows", unreadRows);
    }

    @PostMapping("/sendMessage")
    @ApiOperation("模拟系统发送消息")
    public R sendMessage(@Valid @RequestBody SendMessageForm form) {

        if (!JSONUtil.isJsonArray(form.getIds())) {
            throw new EmosException("请输入用户id组成的JSON数组");
        }
        List<Integer> IDList = JSONUtil.parseArray(form.getIds()).toList(Integer.class);
        MessageEntity entity = new MessageEntity();
        entity.setSenderId(0);
        entity.setSenderName("系统消息");
        entity.setUuid(IdUtil.simpleUUID());
        entity.setMsg(form.getMessage());
        entity.setSendTime(new Date());
        entity.setSenderPhoto("https://static-wx-emos-1307625276.cos.ap-shanghai.myqcloud.com/img/system-photo/system.jpeg");
        /*给包含的每个用户发送信息*/
        IDList.forEach(id -> messageTask.sendAsync(id + "", entity));

        return R.ok().put("result", "发送成功！");
    }
}